// src/utils/request.ts
import axios from 'axios';
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';

// 定义接口响应数据结构
export interface ApiResponse<T = any> {
    code: number;
    data: T;
    message: string;
    success: boolean;
}

// 扩展请求配置接口 - 支持动态 baseURL
interface RequestConfig extends AxiosRequestConfig {
    headers?: any;
    responseType?: 'json' | 'blob' | 'arraybuffer';
    manualToast?: boolean;
    isFormData?: boolean;
    dynamicBaseURL?: string; // 支持动态设置 baseURL
}

// 创建默认的 axios 实例（不设置固定 baseURL）
const service: AxiosInstance = axios.create({
    timeout: 15000,
    headers: {
        'Content-Type': 'application/json',
    },
});

// 请求拦截器
service.interceptors.request.use(
    (config: any) => {
        // 优先级：动态baseURL > 环境变量baseURL > 相对路径
        if (config.dynamicBaseURL) {
            config.baseURL = config.dynamicBaseURL;
        } else if (import.meta.env.VITE_API_BASE_URL) {
            config.baseURL = import.meta.env.VITE_API_BASE_URL;
        }
        // 如果没有设置baseURL，则使用相对路径

        config.headers = config.headers || {};

        // 添加 token
        const token = localStorage.getItem('token') || sessionStorage.getItem('token');
        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
        }

        // 处理 FormData
        if (config.data instanceof FormData || config.isFormData) {
            // 对于 FormData，让浏览器自动设置 Content-Type 和 boundary
            if (config.headers) {
                delete config.headers['Content-Type'];
            }
        }

        // 添加时间戳防止缓存（仅对 GET 请求）
        if (config.method?.toLowerCase() === 'get') {
            config.params = {
                ...config.params,
                _t: Date.now(),
            };
        }

        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// 响应拦截器
service.interceptors.response.use(
    (response: AxiosResponse) => {
        const { data, status } = response;

        if (status >= 200 && status < 300) {
            // 如果后端有统一的响应格式
            if (data && typeof data === 'object') {
                if (data.code === 200 || data.success) {
                    return data.data !== undefined ? data.data : data;
                } else if (status === 200) {
                    return data;
                } else {
                    // 业务错误
                    if (!(response.config as RequestConfig).manualToast) {
                        console.error('业务错误:', data.message || '操作失败');
                    }
                    return Promise.reject(new Error(data.message || '操作失败'));
                }
            }
            return data;
        } else {
            return Promise.reject(new Error(`HTTP Error: ${status}`));
        }
    },
    (error) => {
        // 错误处理逻辑保持不变
        const { response, code } = error;

        let errorMessage = '网络错误，请检查网络连接';

        if (response) {
            switch (response.status) {
                case 401:
                    errorMessage = '未授权，请重新登录';
                    localStorage.removeItem('token');
                    sessionStorage.removeItem('token');
                    window.location.href = '/login';
                    break;
                case 403:
                    errorMessage = '拒绝访问';
                    break;
                case 404:
                    errorMessage = '请求的资源不存在';
                    break;
                case 500:
                    errorMessage = '服务器内部错误';
                    break;
                default:
                    errorMessage = response.data?.message || `请求失败: ${response.status}`;
            }
        } else if (code === 'ECONNABORTED') {
            errorMessage = '请求超时';
        }

        if (!error.config?.manualToast) {
            console.error('请求错误:', errorMessage);
        }

        return Promise.reject(error);
    }
);

// 封装通用请求方法 - 支持动态 baseURL
export const request = <T = any>(config: RequestConfig): Promise<T> => {
    return service(config);
};

// 快捷方法 - 都支持动态 baseURL
export const get = <T = any>(url: string, params?: any, config?: RequestConfig) =>
    request<T>({ ...config, url, method: 'get', params });

export const post = <T = any>(url: string, data?: any, config?: RequestConfig) =>
    request<T>({ ...config, url, method: 'post', data });

export const put = <T = any>(url: string, data?: any, config?: RequestConfig) =>
    request<T>({ ...config, url, method: 'put', data });

export const del = <T = any>(url: string, params?: any, config?: RequestConfig) =>
    request<T>({ ...config, url, method: 'delete', params });

// FormData 专用方法
export const postFormData = <T = any>(url: string, data: Record<string, any> | FormData, config?: RequestConfig): Promise<T> => {
    let formData: FormData;

    if (data instanceof FormData) {
        formData = data;
    } else {
        formData = new FormData();
        Object.keys(data).forEach(key => {
            if (data[key] !== undefined && data[key] !== null) {
                formData.append(key, data[key]);
            }
        });
    }

    return request<T>({
        ...config,
        url,
        method: 'post',
        data: formData,
        isFormData: true,
    });
};

// 创建多个服务的实例（如果需要）
export const createApiService = (baseURL: string): AxiosInstance => {
    const instance = axios.create({
        baseURL,
        timeout: 15000,
    });

    // 可以为此实例添加特定的拦截器
    instance.interceptors.request.use(
        (config) => {
            const token = localStorage.getItem('token');
            if (token) {
                config.headers = config.headers || {};
                config.headers.Authorization = `Bearer ${token}`;
            }
            return config;
        }
    );

    return instance;
};

export default service;